<script setup lang="ts">
import type { ButtonOnGetphonenumberEvent } from '@uni-helper/uni-app-types'
import { uploadFileAPI } from '@/apis/uploadFile'
import { updateProfileAPI } from '@/apis/updateProfile'
import { useUserInfoStore } from '@/store/userInfo'
import { getPhoneNumberAPI } from '@/apis/getPhoneNumber'

const router = useRouter()
const userInfoStore = useUserInfoStore()

const isFinishProfileMode = ref(false)

onLoad((options) => {
  if (options?.finish_mode)
    isFinishProfileMode.value = true
})

const handleChooseAvatar = useThrottleFn(async (e: any) => {
  const url = e.detail.avatarUrl
  try {
    const res = await uploadFileAPI({ tempFilePath: url, fileType: 'image' }, userInfoStore.userInfo!.token!)
    if (res.data) {
      const resData = JSON.parse(res.data)
      const uploadRes = await updateProfileAPI({
        nickname: userInfoStore.userInfo?.nickname || '',
        avatar: resData.data.fullurl,
      }, userInfoStore.userInfo!.token!)
      if ((uploadRes.data as any).code === 1) {
        userInfoStore.setUserInfo({
          ...userInfoStore.userInfo!,
          avatar: resData.data.fullurl,
        })
        uni.showToast({ title: '上传成功', icon: 'none' })
      }
      else {
        uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
      }
    }
    else {
      uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: '上传失败，请稍后重试', icon: 'none' })
  }
}, 1000)

async function handleGetPhoneNumber(e: ButtonOnGetphonenumberEvent) {
  try {
    const res = await getPhoneNumberAPI({
      code: e.detail.code!,
    }, userInfoStore.userInfo!.token!)

    if (res.data?.code === 1) {
      const phoneNumber = res.data?.data
      const userInfoWithPhoneNumber: UserInfo = { ...userInfoStore.userInfo!, mobile: phoneNumber }
      userInfoStore.setUserInfo(userInfoWithPhoneNumber)
    }
    else {
      uni.showToast({ title: '绑定手机号失败', icon: 'none' })
    }
  }
  catch (err) {
    uni.showToast({ title: JSON.stringify(err), icon: 'none' })
  }
}

const handleSubmit = useThrottleFn(async (e: any) => {
  if (e.detail.value.nickname) {
    try {
      const res = await updateProfileAPI({
        nickname: e.detail.value.nickname,
        avatar: userInfoStore.userInfo?.avatar || '',
      }, userInfoStore.userInfo!.token!)
      if ((res.data as any).code === 1) {
        userInfoStore.setUserInfo({
          ...userInfoStore.userInfo!,
          nickname: e.detail.value.nickname,
        })
        if (isFinishProfileMode.value)
          router.replaceAll('home')
        else
          router.back()
      }
      else {
        uni.showToast({ title: '修改失败', icon: 'none' })
      }
    }
    catch (err) {
      uni.showToast({ title: '修改失败，请稍后重试', icon: 'none' })
    }
  }
  else {
    uni.showToast({ title: '请输入昵称', icon: 'none' })
  }
}, 1000)
</script>

<template>
  <Spacer height="30" />
  <view class="overflow-hidden rounded-10rpx bg-white">
    <form class="rounded-10rpx bg-white" @submit="handleSubmit">
      <button
        open-type="chooseAvatar" :style="{ padding: 0, margin: 0, background: 'none' }"
        @chooseavatar="handleChooseAvatar"
      >
        <ListCell label="头像">
          <image class="my-20rpx h-80rpx w-80rpx rounded-full" :src="userInfoStore.userInfo?.avatar" />
        </ListCell>
      </button>
      <Divider color="#F0F0F0" />
      <ListCell label="昵称">
        <input name="nickname" type="nickname" class="h-116rpx rounded-10rpx bg-white text-right text-28rpx text-#333333 leading-28rpx" :value="userInfoStore.userInfo?.nickname">
      </ListCell>
      <ListCell label="手机号">
        <view v-if="userInfoStore.userInfo?.mobile" class="h-137rpx flex flex-col justify-center text-28rpx text-#333333">
          {{ userInfoStore.userInfo?.mobile }}
        </view>
        <button v-else open-type="getPhoneNumber" class="h-137rpx w-620rpx flex items-center justify-center rounded-none bg-#4999F7 text-36rpx text-white font-medium leading-50rpx" @getphonenumber="handleGetPhoneNumber">
          绑定手机号
        </button>
      </ListCell>
      <button name="submit" form-type="submit" class="fixed bottom-80rpx h-96rpx w-702rpx flex items-center justify-center rounded-50rpx bg-#4999F7 text-32rpx text-white font-bold leading-32rpx x-center" hover-class="bg-brand">
        确认修改
      </button>
    </form>
  </view>
</template>

<route lang="yaml">
name: 'profileSettings'
style:
  navigationBarTitleText: '设置'
</route>
